package com.sd.repay.service.impl;

import com.sd.repay.common.Constants;
import com.sd.repay.dao.BaseDao;
import com.sd.repay.service.ActivateService;
import com.sd.repay.utils.StringUtil;
import com.sd.repay.utils.WebUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author sd
 * @Description: 激活码服务类
 * @date 2018年09月02日
 */
@Service
public class ActivateServiceImpl implements ActivateService {

    private static Logger log = LoggerFactory.getLogger(ActivateServiceImpl.class);

    @Autowired
    private BaseDao baseDao;


    /**
     * 生成激活码（同一时间只能单一线程执行）
     *
     * @param length
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public boolean genertateActivateCode(int length, String oemType) throws Exception {

        if (length < 1) {
            return false;
        }

        String sql = " INSERT INTO t_activate_code(activate_code, oem_type, create_time) VALUES(?,?,?) ";
        List<Object[]> paramsList = new ArrayList<>();
        List<Object> paramsObj = null;
        String activateCode = "";

        for (int index = 0; index < length; index++) {
            activateCode = WebUtil.genUUID();

            paramsObj = new ArrayList<>();
            paramsObj.add(activateCode);
            paramsObj.add(oemType);
            paramsObj.add(new Date());
            paramsList.add(paramsObj.toArray());

        }
        int[] result = baseDao.batchExecute(sql, paramsList);
        log.info("生成" + length + "数量的激活码影响的行数：" + result.length);
        if (result.length != length) {
            throw new RuntimeException("批量新增激活码失败，请核查数据后操作");
        }
        return true;
    }

    /**
     * 根据编码获取激活码
     *
     * @param code
     * @return
     */
    @Override
    public Map<String, Object> getActivateByCode(String code) throws Exception {

        String sql = " SELECT * FROM t_activate_code WHERE activate_code = ? ";
        return baseDao.findFirst(sql, code);
    }

    /**
     * 根据代理商编号获取激活码
     *
     * @param agentNo
     * @return
     */
    @Override
    public List<Map<String, Object>> getActivateByAgentNo(String agentNo) throws Exception {

        String sql = " SELECT * FROM t_activate_code WHERE agent_no = ? ";
        return baseDao.findList(sql, agentNo);
    }

    /**
     * 根据商户号号获取激活码
     *
     * @param merNo
     * @return
     */
    @Override
    public Map<String, Object> getActivateByMerNo(String merNo) throws Exception {

        String sql = " SELECT * FROM t_activate_code WHERE merchant_no = ? ";
        return baseDao.findFirst(sql, merNo);
    }

    /**
     * 根据序列号范围获取激活码（包含首尾）
     *
     * @param beginIndex
     * @param endIndex
     * @return
     */
    @Override
    public List<Map<String, Object>> getActivateByIndex(int beginIndex, int endIndex) throws Exception {

        String sql = " SELECT * FROM t_activate_code WHERE id >= ? AND id <= ?";
        return baseDao.findList(sql, new Object[]{beginIndex, endIndex});
    }

    /**
     * 分配激活码
     *
     * @param agentNo
     * @param agentNode
     * @param oneAgentNo
     * @return
     */
    @Override
    public int allotActivateCode(String agentNo, String agentNode, String oneAgentNo, int beginIndex, int endIndex) throws Exception {

        String sql = " UPDATE t_activate_code SET agent_no = ?, agent_node = ?, one_agent_no = ?, status = ? " +
                " WHERE id >= ? AND id <= ? AND status = ? AND can_use = ? ";
        return baseDao.execute(sql, new Object[]{agentNo, agentNode, oneAgentNo, Constants.ACTIVATE_STATUS_ALLOT,
                beginIndex, endIndex, Constants.ACTIVATE_STATUS_DEPOT, Constants.ACTIVATE_CAN_USE});
    }

    /**
     * 激活码激活
     *
     * @param merchantNo
     * @param code
     * @return
     */
    @Override
    public int activateCode(String merchantNo, String code) throws Exception {

        String sql = " UPDATE t_activate_code SET merchant_no = ?, status = ?, activate_time = ? WHERE activate_code = ? AND status = ? AND can_use = ? ";
        return baseDao.execute(sql, new Object[]{merchantNo, Constants.ACTIVATE_STATUS_ACTIVE, new Date(), code, Constants.ACTIVATE_STATUS_ALLOT, Constants.ACTIVATE_CAN_USE});
    }

    /**
     * 获取最大序列号(ID)
     *
     * @return
     * @throws Exception
     */
    @Override
    public Integer getMaxActivateIndex() throws Exception {

        String sql = " SELECT MAX(id) AS maxIndex FROM t_activate_code ";
        Map<String, Object> resMap = baseDao.findFirst(sql);
        if (resMap == null || resMap.isEmpty()) {
            return 0;
        }
        String maxIndexStr = StringUtil.filterNull(resMap.get("activate_index"));
        try {
            return Integer.parseInt(maxIndexStr);
        } catch (Exception e) {
            return 0;
        }
    }
}